package com.jh.jingfei.main.ui;

import android.content.Context;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.PopupWindow;

import com.jh.jingfei.R;
import com.jh.jingfei.home.ParamListFragment;
import com.jh.jingfei.main.adapter.CrewRvAdapter;
import com.jh.jingfei.main.event.StartBrotherEvent;
import com.jh.jingfei.models.RobotGroup;
import com.jh.jingfei.repositories.RobotGroupRepository;
import com.jh.jingfei.widget.MyToolbar;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadmoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.strongloop.android.loopback.RestAdapter;
import com.strongloop.android.loopback.callbacks.ListCallback;

import org.greenrobot.eventbus.EventBus;

import java.util.List;

import me.yokeyword.fragmentation_swipeback.SwipeBackFragment;

/**
 * Home (首页)
 *
 * @author lxb
 */
public class HomeFragment extends SwipeBackFragment {

    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";

    private String mParam1;
    private String mParam2;

    private MyToolbar toolbar;
    private PopupWindow popupWindow;

    private SmartRefreshLayout refreshLayout;
    private RecyclerView crewRv; // 机组 RecycleView
    private CrewRvAdapter crewRvAdapter;
    private RobotGroupRepository rgp;
    private int limit = 10;
    private int offset = 0;

    public HomeFragment() {
        // Required empty public constructor
    }

    public static HomeFragment newInstance(String param1, String param2) {
        HomeFragment fragment = new HomeFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }

        RestAdapter restAdapter = new RestAdapter(this.getContext(), getString(R.string.base_url));
        rgp = restAdapter.createRepository(RobotGroupRepository.class);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_home, container, false);
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        toolbar = view.findViewById(R.id.home_top_toolbar);
        toolbar.setTitle(R.string.home_name);
        toolbar.setNavigationIcon(null);

        refreshLayout = view.findViewById(R.id.refresh_layout);
        crewRv = view.findViewById(R.id.crew_rv);
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        toolbar.setOnRightMenuClickListener(new MyToolbar.OnRightMenuClickListener() {
            @Override
            public void onClick(View v) {
                showPopWin(v);
            }
        });

        crewRvAdapter = new CrewRvAdapter(getContext());
        crewRvAdapter.setOnItemClickListener(new CrewRvAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(int position) {
                ParamListFragment paramListFragment = ParamListFragment.newInstance("", "");
                EventBus.getDefault().post(new StartBrotherEvent(paramListFragment));
            }
        });
        GridLayoutManager gridLayoutManager = new GridLayoutManager(getContext(), 2);
        crewRv.setLayoutManager(gridLayoutManager);
        crewRv.setAdapter(crewRvAdapter);

        refreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                offset = 0;
                loadRobotGroupData(limit, offset);
            }
        });
        refreshLayout.setOnLoadmoreListener(new OnLoadmoreListener() {
            @Override
            public void onLoadmore(RefreshLayout refreshlayout) {
                offset += 1;
                loadRobotGroupData(limit, offset);
            }
        });
        refreshLayout.autoRefresh();
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
    }

    @Override
    public void onDetach() {
        super.onDetach();
    }

    private void showPopWin(View v) {
        if (popupWindow == null) {
            View contentView = LayoutInflater.from(getContext()).inflate(R.layout.home_right_pop_win, null);
            popupWindow = new PopupWindow(contentView,
                    ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT, true);

            popupWindow.setTouchable(true);
            popupWindow.setBackgroundDrawable(new ColorDrawable());
        }
        if (popupWindow.isShowing()) {
            popupWindow.dismiss();
        } else {
            popupWindow.showAsDropDown(v);
        }
    }

    private void loadRobotGroupData(int limit, final int offset) {
        rgp.findAll(limit, offset, new ListCallback<RobotGroup>() {
            @Override
            public void onSuccess(List<RobotGroup> objects) {
                Log.i("LOADRobot", objects.toString());

                finishLoadData(offset == 0);
                if (offset == 0) {
                    crewRvAdapter.updateItems(objects);
                } else {
                    crewRvAdapter.addItems(objects);
                }
            }

            @Override
            public void onError(Throwable t) {
                Log.i("LOADRobot", t.toString());

                finishLoadData(offset == 0);
            }
        });
    }

    private void finishLoadData(boolean isRefresh) {
        if (isRefresh) {
            refreshLayout.finishRefresh();
        } else {
            refreshLayout.finishLoadmore();
        }
    }
}
